<?php
/**
*+---------------------用户操作类------------------+
*+-------------------------------------------------+
*+-----用户登录注册，设置昵称，重置密码------------+
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/

namespace Home\Controller;
use User\Api\UserApi;

use Api\Event\CacheEvent;
use Common\Util\ThinkSDK\ThinkOauth;

class UserController extends HomeController {
    /**
    *开放操作，非登录下
    */
    static $openAction = array('register', 'login', 'logout', 'send_sms_code', 'verify', 'retrieve', 'ssologin', 'nickname');

    protected function _initialize(){
        parent::_initialize();
 
        C('DEFAULT_THEME', 'ui3');
        // define('UID', is_login(1));
        if (!defined('IS_MOBILE')){
            define('IS_MOBILE', is_mobile_request());
        }
        if (!in_array(ACTION_NAME, self::$openAction)  && !UID) {
            $sso = mobileBrower();
            if ($sso && IS_MOBILE){
                return $this->redirect('User/ssologin');
            }
            return $this->redirect('User/login');
        }

    }


    /* 注册页面 */
    public function register(){

        if(IS_POST){
            $data = I('');

            $baseObj = A('Api/User', 'Event');
            $res = $baseObj->register($data);
            if($res['code'] != 200){
                
                $this->ajaxReturn(array('state'=>-1, 'info'=>$res['info']));

            }else{
                $redirect_url = U('user/nickname');
                $platform = $data['platform'];
                if (isset($platform) && $platform == 5) {
                    $registerResult = event('User')->genToken($res['uid'], '', '', $platform);
                    $redirect_url = U('regreturn', ['appToken' => $registerResult['data']['appToken']]);
                }
                session('_login_user_id', $res['uid']);
                session('_login_type', 'web');
                $this->ajaxReturn(array('state'=>0, 'url'=>$redirect_url, 'info'=>'注册成功'));
            }
        } else {
            $sns = ThinkOauth::getInstance('sina');
            $sso_code_uri['sina'] = $sns->code($redirect_url);
            $sns = ThinkOauth::getInstance('qq');
            $sso_code_uri['qq'] = $sns->code();
            $sns = ThinkOauth::getInstance('weixin');
            $sso_code_uri['weixin'] = $sns->code($redirect_url);

            $this->assign('sso_code_uri', $sso_code_uri);
            $this->assign('title', '用户注册');
            $this->assign('currentTab', 'registerTab');
            $this->display();
        }
    }

    // public function ssologin()
    // {
    //     $channel = I('channel');
    //     if (!$channel ){
    //         return $this->error(['info' => '登录失败']);
    //     }

    //     $openUser = [
    //         'openid' => I('openid'),
    //         'nickname' => I('nickname'),
    //         'avatar' => I('avatar'),
    //     ];
    //     $uid = event('User')->ssoLogin($channel, $openUser['openid'], $openUser['nickname'], $openUser['avatar']);
    //     if (!$uid){
    //         return $this->error(['info' => '登录失败']);
    //     }else{
    //         $Member = D('Member');
    //         $user = $Member->login($uid);
    //         if($user === false){
    //             return $this->error(['info' => '登录失败']);
    //         }elseif(empty($user['nickname'])){
    //             return $this->success(['code' => 1, 'info' => '请设置昵称']);
    //         }else {
    //             return $this->success('登录成功');
    //         }
    //     }
    //     return;
    // }

    public function ssologin()
    {
        $this->title = "授权登录";
        if (IS_MOBILE){
            C('DEFAULT_THEME', 'mobile2');
            $sso = mobileBrower();
            if ($sso){
                $this->assign('sso', $sso);
                switch ($sso) {
                    case 'sina':
                        $sns = ThinkOauth::getInstance('sina');
                        $sso_code_uri = $sns->code($redirect_url);
                        break;
                    case 'qq':
                        $sns = ThinkOauth::getInstance('qq');
                        $sso_code_uri = $sns->code($redirect_url);
                        break;
                    case 'weixin':
                        $sns = ThinkOauth::getInstance('weixin');
                        $sso_code_uri = $sns->code($redirect_url);
                        break;    
                    default:
                        break;
                }
                $this->assign('sso_code_uri', $sso_code_uri);
            }
            $this->display();
            return;
        }
        $this->redirect('User/login');
    }

    /* 登录页面 */
    public function login(){
        $errorTimes = session('LOGIN_ERROR_TIMES');
        $this->title ="用户登录";
        if(IS_POST){
            $data = I('');
            if($errorTimes>=3){
                if(empty($data['verify']))
                    // $this->ajaxReturn(array('state'=>-1, 'info'=>'请填写验证码', 'errorTimes'=>$errorTimes));

                if(!check_verify($data['verify']))
                    // $this->ajaxReturn(array('state'=>-2, 'info'=>'验证码输入错误！', 'errorTimes'=>$errorTimes));
                
                unset($data['verify']);
            }
            
            $baseObj = A('Api/User', 'Event');
            $res = $baseObj->login($data, 'Home');
            if($res['code'] != 200){
                // session('LOGIN_ERROR_TIMES', $errorTimes+1);
                $this->ajaxReturn(array('state'=>-3, 'info'=>$res['info'], 'errorTimes'=>$errorTimes+1));
            }else{
                $msg = '登录成功！';

                $Member = D('Member');
                $user=$Member->login($res['data']['uid']);
                if($user === false){
                    session('LOGIN_ERROR_TIMES', $errorTimes+1);
                    $this->ajaxReturn(array('state'=>-4, 'info'=>$Member->getError()));

                }elseif(empty($user['nickname'])){
                    session('_login_user_id', $res['data']['uid']);
                    session('_login_auto', $data['auto']);
                    session('_login_type', 'web');
                    $jumpUrl = U('User/nickname');

                    // modify by liubo at 2016-05-25
                    $this->ajaxReturn(['state' => -5, 'url' => $jumpUrl, 'info' => $Member->getError(), 'errorTimes' => 0]);
                }else {
                    //$jumpUrl = $_SERVER["HTTP_REFERER"];
                    $jumpUrl = cookie('redirect_url') ?: U('Visitor/index');
                }

                session('LOGIN_ERROR_TIMES', null);

                //start add auto login by susy.liang<liangling@ilongyuan.com.cn> at 2015/7/7
                if($data['auto']){
                    /*$cilentIP = get_client_ip(1);
                    $autoVal = $user['uid'].'|'.$user['nickname'].'|'.$cilentIP;
                    $autoVal = check_auto_login($autoVal);
                    setcookie('autologin', $autoVal, time()+C('AUTO_LOGIN_EXPIRE'));*/

                    // 2015-7-20 11:23:15 Legend.  重写

                        $salt  = rand(100000, 999999);
                        $cookie_auth = array(
                            'salt'           => $salt,  // 加盐
                            'auto_username'  => $user['mobile'], 
                            'key'            => C('API_AUTH_KEY'),   // 密钥
                            'password'       => $user['password']
                        );
                        $token = data_auth_sign($cookie_auth);
                        // 使用TP内部函数处理
                        cookie('salt',      $salt,'prefix=login&expire='.(3600*24*14));
                        cookie('token',     $token,'prefix=login&expire='.(3600*24*14));
                        cookie('auto_username', $user['mobile'],'prefix=login&expire='.(3600*24*14));
                        cookie('auto_login',  1,'prefix=login&expire='.(3600*24*14));
                }
                //end
                $this->ajaxReturn(array('state'=>0, 'info'=>$msg, 'url'=>$jumpUrl, 'errorTimes'=>0));
            }

        } 
        // GET
        else {
            $redirect_url = I('redirect_url') ?: ( cookie('redirect_url') ?: 'Visitor/index');
            $this->errorTimes = $errorTimes;
            if(session('home_user_auth'))
            {
                $this->redirect($redirect_url);
            }
            else
            {
                if (IS_MOBILE){
                    C('DEFAULT_THEME', 'mobile2');
                    $sso = mobileBrower();
                    $this->assign('sso', $sso);
                }else{

                    $sns = ThinkOauth::getInstance('sina');
                        $sso_code_uri['sina'] = $sns->code($redirect_url);
                    $sns = ThinkOauth::getInstance('qq');
                        $sso_code_uri['qq'] = $sns->code();
                    $sns = ThinkOauth::getInstance('weixin');
                        $sso_code_uri['weixin'] = $sns->code($redirect_url);
                    $this->assign('sso_code_uri', $sso_code_uri);
 
                }
                $this->assign('title', '登录');
                $this->assign('currentTab', 'loginTab');
                $this->display();
            }
        }
    }

    /* 退出登录 */
    public function logout(){
        if(UID){
            D('Member')->logout();
            $this->redirect('visitor/home');

        } else {

            $this->redirect('User/login');

        }
    }

    /* 验证码，用于登录和注册 */
    public function verify(){
        $verify = new \Think\Verify();
        $verify->entry(1);
    }


    /**
     * 修改密码提交
     */
    public function resetPwd(){
        if ( IS_POST ) {
            $data = I('');
            //$data['uid'] = UID;
            $baseObj = A('Api/User', 'Event');
            $res = $baseObj->resetPwd(UID, $data);
            if($res['code'] == 200){
                D('member')->logout();
                $this->ajaxReturn(array('state'=>0, 'info'=>'密码修改成功', 'url'=>U('User/login')));

            }else{

                $this->ajaxReturn(array('state'=>-1, 'info'=>$res['info']));
            }
        }else{
            $this->display('password');
        }
    }

    /**
    *手机验证码
    *默认是注册时发验证码
    */
    public function send_sms_code(){
        $now = time();
        if(!check_verify(I('verify', '', 'trim'))){
            $this->error('验证码输入错误！');
        }
        if (session('sendsms_lastime') && session('sendsms_lastime') > $now - 60){
            $this->error('操作频繁');
        }
        session('sendsms_lastime', $now);

        $data = I('');
        if (!empty($data['mobile'])) {
            try {
                $Redis = CacheEvent::instance(0);
                $key = 'IMBA.USER.REGISTER.SMS_TIMES';
                $times = $Redis->hGet($key, $data['mobile']);
                $times = intval($times);
                if ($times >= 5) {
                    $this->error('该手机号码操作过于频繁，请稍后重试');
                }
                $exists = $Redis->exists($key);
                $times = intval($times);
                if (!$exists) {
                    $pipe = $Redis->multi(\Redis::PIPELINE);
                    $pipe->hSet($key, $data['mobile'], $times+1);
                    $pipe->expireAt($key, strtotime(date('Ymd', strtotime('+1 day'))));
                    $pipe->exec();
                } else {
                    $Redis->hSet($key, $data['mobile'], $times+1);
                }
                unset($Redis);
                $times = intval($times);
            } catch(\Exception $e) {
                \Think\Log::record('[SEND SMS] - REDIS ERROR!! '.$e->getMessage(), 'ERROR');
            }
        }

        \Think\Log::record('[SEND SMS DATA] - '.json_encode($data), 'DEBUG');
        $baseObj = A('Api/User', 'Event');

        //$flg true|注册时 false|找回密码
        $flg = !empty($data['type'])?false:true;

        $res = $baseObj->sendSms($data, $flg);

        if($res['code'] == 200)
            $this->success($res['info']);
        else
            $this->error($res['info']);
    }

    /**
    *头像上传
    */
    public function avatar(){

        if(IS_POST){

            $data = I('');
            if(empty($data))
                $this->error('提交信息不能为空');

            $update = array();
            if($data['avatar']){
                //TODO:调用crop 进行头像的裁剪
                $update['avatar'] = $data['avatar'];
            }

            if($data['background']){
                //TODO:调用crop 进行头像的裁剪
                $update['background'] = $data['background'];
            }

            if(service('Users')->updateUserFields(UID, '', $update, false)){
                if($data['avatar']){
                    $user = session('home_user_auth');
                    $user['avatar'] = $data['avatar'];
                    uri_format($user['avatar']);
                    session('home_user_auth', $user);
                    session('home_user_auth_sign', data_auth_sign($user));
                }               

                $this->ajaxReturn(array('state'=>0, 'info'=>'上传成功'));

            }else
                $this->ajaxReturn(array('state'=>-1, 'info'=>'上传失败'));

        }else{
            $user = service('Users')->detail(UID);
            uri_format($user['avatar']);
            uri_format($user['background']);
            $this->avatar = $user['avatar'];
            $this->background = $user['background'];
            $this->display();
        }
    }

    /**
    *图像根据坐标和宽高进行裁剪
    *@param string $path 图像相对路径
    *@param int $width 裁剪的宽
    *@param int $height 裁剪的高
    *@param int $x 裁剪起始的x坐标
    *@param int $y 裁剪起始的y坐标
    *@return string 裁剪后的图片存储的相对路径
    *@author susy<susy.liang@ilongyuan.com.cn>
    */
    private function crop($path='', $width=0, $height=0, $x=0, $y=0){
        $imgObj = new \Think\Image();
        
        if(!$path)
            return false;

        if(substr($path, 0, 1) != '.')
            $path = '.'.$path;

        $imgObj->open($path);

        $image->crop($width, $height, $x, $y)->save($path);
    }


    /**
    *设置昵称
    */
    public function nickname(){
        $redirect_url = I('redirect_url') ?: (cookie('redirect_url') ?: U('Index/index'));
        $uid = UID ?: intval(session('_login_user_id'));

        if (!$uid) {
            if (IS_POST) {
                $this->ajaxReturn(array('state'=>-2, 'info'=>'未登录'));
            }
            return $this->redirect('User/login');
        }
        if(IS_POST){
            $nickname = I('nickname', '', 'strip_tags');
            $data = array(
                    'uid'=>$uid,
                    'nickname'=>$nickname,
                );
            $baseObj = A('Api/User', 'Event');
            $res = $baseObj->setNickname($data);
            if($res['code'] == 200){
                $Member = D('Member');
                $user = $Member->login($uid);
                if (!$user) {
                    $this->ajaxReturn(array('state'=>-1, 'info'=>'未登录'));
                }

                session('LOGIN_ERROR_TIMES', null);

                $autoLogin = session('_login_auto');
                if($autoLogin){
                    $salt  = rand(100000, 999999);
                    $cookie_auth = array(
                        'salt'           => $salt,  // 加盐
                        'auto_username'  => $user['mobile'], 
                        'key'            => C('API_AUTH_KEY'),   // 密钥
                        'password'       => $user['password']
                    );
                    $token = data_auth_sign($cookie_auth);
                    // 使用TP内部函数处理
                    cookie('salt',      $salt,'prefix=login&expire='.(3600*24*14));
                    cookie('token',     $token,'prefix=login&expire='.(3600*24*14));
                    cookie('auto_username', $user['mobile'],'prefix=login&expire='.(3600*24*14));
                    cookie('auto_login',  1,'prefix=login&expire='.(3600*24*14));
                }
                session('_login_user_id', null);
                $this->ajaxReturn(array('state'=>0, 'info'=>$msg, 'url'=>$redirect_url, 'errorTimes'=>0));
            }
            else{
                $this->ajaxReturn(array('state'=>-1, 'info'=>$res['info']));
                //$this->error($res['info']);
            }
            
        }else{
            if(session('home_user_auth.nickname')){
                return $this->redirect('Index/index');
            }
            $this->userInfo = array(
                    'id'=>$uid,
                    'nickname'=>'',
                    'avatar' => '',
                );
            if (session('oss_login.from') == 'pc'){
                $redirect_url = U('loginreturn', ['appToken' => session('oss_login.token')]);
            }
            $this->assign('redirect_url', $redirect_url);
            //$this->assign('userInfo', $userInfo);
            if (IS_MOBILE){
                C('DEFAULT_THEME', 'mobile2');
            }

            // 判断是否第三方登录
            if (session('_login_type') == 'web') {
                $this->type = 'web';
            } else {
                $this->type = 'sso';
                $sso_channel = '第三方';
                switch (cookie('sso_channel')) {
                    case 'qq':
                        $sso_channel = 'QQ';
                        break;
                    case 'weixin':
                        $sso_channel = '微信';
                        break;
                    case 'sina':
                        $sso_channel = '微博';
                        break;
                    case 'stargame':
                        $sso_channel = 'STARGAME';
                }
                $this->assign('sso_channel', $sso_channel);

                $this->assign('sso_avatar', cookie('sso_avatar'));
                $this->assign('sso_nickname', cookie('sso_nickname'));
            }

            if (session('oss_login.from') == 'pc') {
                $this->redirect_url = U('User/loginreturn', ['appToken' => session('oss_login.token')]);
                C('DEFAULT_THEME', 'ui2');
                return $this->display('pcnickname');
            }
            $this->title = "设置昵称";
            return $this->display();
        }
    }

    public function loginreturn()
    {
        echo '登录成功,正在跳转...';
        exit;
    }

    public function regreturn()
    {
        echo '注册成功,正在跳转...';
        exit;
    }

    /**
    *找回密码
    */
    public function retrieve(){

        if(IS_POST){

            $data = I('');
            $baseObj = A('Api/User', 'Event');
            $res = $baseObj->retrieve($data);

            if($res['code'] == 200){
                $this->ajaxReturn(array('state'=>0, 'info'=>'密码找回成功', 'url'=>U('User/login')));
            }else{
                $this->ajaxReturn(array('state'=>-1, 'info'=>$res['info']));
            }
            
        }else{

            $this->display('lost');
        }
        
    }

    /**
     * 用户反馈
     *@author susy.liang<liangling@ilongyuan.com.cn>
     */
    public function feedback() {
        $data = I('');
        $res = A( 'Api/Feedback', 'Event')->add(UID, $data['type'], $data['content']);
        if($res)
            $this->ajaxReturn(array('state'=>0, 'info'=>'反馈成功'));
        else
            $this->ajaxReturn(array('state'=>-1, 'info'=>'反馈失败,请联系管理员'));
    }


}
